package com.live.task;

import java.net.URI;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import com.live.common.Constant;
import com.live.tools.LiveTools;

public class LiveDetail extends AsyncTask<Bundle, Integer, String> {

	private Context context = null;

	private String matchId = null;

	private String matchOptaId = null;

	private String type = null;

	public LiveDetail(Context context, String type) {
		this.context = context;
		this.type = type;
	}

	// 此方法在主线程执行,当任务执行之前开始调用此方法，可以在这里显示进度对话框
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		Log.i("PageTask", "onPreExecute()  " + Thread.currentThread().getId());
	}

	// 此方法在后台线程执行，完成任务的主要工作，通常需要较长的时间。
	// 在执行过程中可以调用publicProgress(Progress...)来更新任务的进度。

	@Override
	protected String doInBackground(Bundle... params) {
		Log.i("PageTask", "doInBackground... " + Thread.currentThread().getId());

		matchId = params[0].getString("matchId");
		matchOptaId = params[0].getString("matchOptaId");

		String url = Constant.SITE_URL + "live_detail.php?locale=" + LiveTools.getLocaleLanguage() + "&";
		url += "matchId=" + matchId + "&matchOptaId=" + matchOptaId;

		// 取得本机MAC地址
		String mac = LiveTools.getLocalMacAddress(context);
		if (mac == null) {
			mac = "android%20AVD";
		}
		// 此URL记录观看比赛者
		SharedPreferences store = context.getSharedPreferences(Constant.PREFS_NAME, 0);
		url += "&id=" + store.getString("id", null) + "&mac=" + mac + "&t=" + type;

		// 记录观看比赛详细页的信息
		setMatchDetail(url);

		publishProgress();
		return null;
	}

	// 此方法在主线程执行，用于显示任务执行的进度
	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		Log.i("PageTask", "onProgressUpdate()  " + Thread.currentThread().getId());
	}

	// 此方法在主线程执行，任务执行的结果作为此方法的参数返回。
	@Override
	protected void onPostExecute(String result) {
		Log.i("PageTask", "onPostExecute()  " + Thread.currentThread().getId());
	}

	/**
	 * 记录观看比赛详细页的信息
	 * 
	 * @param url
	 * @return
	 */
	private void setMatchDetail(String url) {
		HttpClient client = new DefaultHttpClient();

		// 提拱默认的HttpClient实现
		HttpPost request;
		try {
			request = new HttpPost(new URI(url));
			client.execute(request);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}